package com.leetcode.q6;

import java.util.ArrayList;
import java.util.List;

/**
 * <p> description: desc</p>
 *
 * @author tanzc
 * @date 2022/3/29
 **/
public class Convert {
    public String convert2(String s, int numRows) {
        if (numRows == 1) {
            return s;
        }
        int unit = numRows * 2 - 2;
        int num = s.length() / unit;
        int remainder = s.length() % unit;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j < num; j++) {
                if (i == 0 || i == numRows - 1) {
                    sb.append(s.charAt(unit * j + i));
                } else {
                    sb.append(s.charAt(unit * j + i));
                    sb.append(s.charAt(unit * (j + 1) - i));
                }
            }
            if (remainder != 0) {
                if (i == 0 || i == numRows - 1) {
                    if (unit * num + i < s.length()) {
                        sb.append(s.charAt(unit * num + i));
                    }
                } else {
                    if (unit * num + i < s.length()) {
                        sb.append(s.charAt(unit * num + i));
                    }
                    if (unit * (num + 1) - i < s.length()) {
                        sb.append(s.charAt(unit * (num + 1) - i));
                    }
                }
            }
        }
        return sb.toString();
    }

    public String convert(String s, int numRows) {
        if (numRows == 1) {
            return s;
        }
        List<StringBuffer> list = new ArrayList<>();
        for (int i = 0; i < numRows; i++) {
            StringBuffer sb = new StringBuffer();
            list.add(sb);
        }
        int listIndex = 0, direction = 1;
        for (int i = 0; i < s.length(); i++) {
            list.get(listIndex).append(s.charAt(i));
            if (listIndex == 0) {
                direction = 1;
            } else if (listIndex == numRows - 1) {
                direction = -1;
            }
            listIndex += direction;
        }
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            stringBuffer.append(list.get(i));
        }
        return stringBuffer.toString();
    }
}
